import io
from requests import get as Get
from PIL import Image, ImageTk, ImageDraw
import cv2
import numpy as np
from colorama import *
import sys

init()


def load_local_pic(path, tag, size=()):
    """加载本地图片"""
    im = Image.open(path)
    if size:
        im = im.resize((int(size[0]), int(size[1])))

    images[tag] = ImageTk.PhotoImage(im)


def load_net_pic(url, tag, size=()):
    """网络图片转可显示图片"""
    data = Get(url).content
    data_stream = io.BytesIO(data)

    pil_image = Image.open(data_stream)

    if size:
        pil_image = pil_image.resize((int(size[0]), int(size[1])))  # 转化图片尺寸

    tk_image = ImageTk.PhotoImage(pil_image)

    images[tag] = tk_image


# def LoadPushPic(url, tag, size=()):
#     """网络图片转可显示图片"""
#     data = Get(url).content
#     data_stream = io.BytesIO(data)
#
#     pil_image = Image.open(data_stream).convert('RGBA')
#
#     if size:
#         pil_image = pil_image.resize((int(size[0]), int(size[1])))  # 转化图片尺寸
#
#     alpha = Image.new('RGBA', (150, 45))
#     draw = ImageDraw.Draw(alpha)
#     draw.rectangle((0, 0, 150, 45), fill=(55, 55, 55, 225))
#     pil_image.paste(alpha, (0, 180), alpha)
#
#     tk_image = ImageTk.PhotoImage(pil_image)
#
#     images[tag] = tk_image
images = {}     # {tag: img}        存储了图片数据


def show_net_pic_windowed(url):
    pass

def get_masks(im):
    hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)  # 色彩空间由RGB转换为HSV

    lower_hsv = np.array([0, 0, 0])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([180, 255, 46])  # 设置要过滤颜色的最大值
    black = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([0, 0, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([180, 43, 220])  # 设置要过滤颜色的最大值
    gray = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([0, 0, 221])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([180, 30, 255])  # 设置要过滤颜色的最大值
    white = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([0, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([10, 255, 255])  # 设置要过滤颜色的最大值
    pink = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([156, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([180, 255, 255])  # 设置要过滤颜色的最大值
    red = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([11, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([25, 255, 255])  # 设置要过滤颜色的最大值
    orange = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([26, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([34, 255, 255])  # 设置要过滤颜色的最大值
    yellow = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([35, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([77, 255, 255])  # 设置要过滤颜色的最大值
    green = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([78, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([99, 255, 255])  # 设置要过滤颜色的最大值
    cyan = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([100, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([124, 255, 255])  # 设置要过滤颜色的最大值
    blue = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    lower_hsv = np.array([125, 43, 46])  # 设置要过滤颜色的最小值
    upper_hsv = np.array([155, 255, 255])  # 设置要过滤颜色的最大值
    purple = cv2.inRange(hsv, lower_hsv, upper_hsv)  # 调节图像颜色信息（H）、饱和度（S）、亮度（V）区间，选择蓝色区域

    return {
        'black': black,
        'gray': gray,
        'white': white,
        'pink': pink,
        'red': red,
        'orange': orange,
        'yellow': yellow,
        'green': green,
        'cyan': cyan,
        'blue': blue,
        'purple': purple,
    }
    # cv2.imshow("video", im)
    # cv2.imshow("black", black)
    # cv2.imshow("gray", gray)
    # cv2.imshow("white", white)
    # cv2.imshow("pink", pink)
    # cv2.imshow("red", red)
    # cv2.imshow("orange", orange)
    # cv2.imshow("yellow", yellow)
    # cv2.imshow("green", green)
    # cv2.imshow("cyan", cyan)
    # cv2.imshow("blue", blue)
    # cv2.imshow("purple", purple)
    #
    # c = cv2.waitKey(40)
    # if c == 27:  # 按键Esc的ASCII码为27
    #     break


COLOR_STRING = {
    'black': Fore.BLACK,
    'gray': Fore.LIGHTBLACK_EX,
    'white': Fore.WHITE,
    'pink': Fore.LIGHTMAGENTA_EX,
    'red': Fore.RED,
    'orange': Fore.LIGHTYELLOW_EX,
    'yellow': Fore.YELLOW,
    'green': Fore.GREEN,
    'cyan': Fore.CYAN,
    'blue': Fore.BLUE,
    'purple': Fore.MAGENTA,
}


def get_char(gray_number):
    # ascii_char = list("$@B%8&WM#")
    ascii_char = list("■●◆")
    length = len(ascii_char)
    unit = (256.0 + 1) / length
    return ascii_char[int(gray_number / unit)]


def load_colored_image(url=None, path=None):
    if path:
        im = cv2.imread(path)
    elif url:
        foo, im = cv2.VideoCapture(url).read()
    
    # scale_percent = 40  # percent of original size
    # width = int(im.shape[1] * scale_percent / 100)
    # height = int(im.shape[0] * scale_percent / 100)
    # dim = (width, height)
    # im = cv2.resize(im, dim, interpolation=cv2.INTER_AREA)
    return im


def print_colored_image(im):
    masks = get_masks(im)
    gray_im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    for y in range(im.shape[0]):
        for x in range(im.shape[1]):
            for color in masks:
                if masks[color][y, x] == 255:
                    break
            # sys.stdout.write(COLOR_STRING[color] + '■')
            sys.stdout.write(COLOR_STRING[color] + get_char(gray_im[y, x]))
            
        sys.stdout.write('\n')

    print('\n\n\n\n\n')

    _im = cv2.imread('bin\\tip.jpg')
    im = cv2.resize(_im, (im.shape[1], _im.shape[0]), interpolation=cv2.INTER_AREA)
    masks = get_masks(im)
    for y in range(im.shape[0]):
        for x in range(im.shape[1]):
            for color in masks:
                if masks[color][y, x] == 255:
                    break
            sys.stdout.write(COLOR_STRING[color] + '■')

        sys.stdout.write('\n')


if __name__ == '__main__':
    print_colored_image(load_colored_image(url='https://www.animefreak.tv/meta/anime/6531/clannad.jpg'))
